package com.ruoyi.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.MySqlDialect;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatis改为mybatisplus
 * @author: diandong滕玉静
 * @date: 2021-10-29
 */
@Configuration
public class MybatisPlusConfig {



    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDbType(DbType.MYSQL);
        paginationInterceptor.setDialect(new MySqlDialect());
        return paginationInterceptor;
    }

    /**
     * 乐观锁
     * 解决报错 Parameter ‘MP_OPTLOCK_VERSION_ORIGINAL‘ not found. Available parameters are [param1, et]
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


    @Component
    public static class MyMetaObjectHandler implements MetaObjectHandler {


        @Override
        public void insertFill(MetaObject metaObject) {
            try{
                LoginUser loginUser = SecurityUtils.getLoginUser();
                this.strictInsertFill(metaObject, "createBy", String.class,loginUser.getUsername() );
                this.strictInsertFill(metaObject, "updateBy", String.class,loginUser.getUsername());
                this.strictInsertFill(metaObject, "userId", Long.class,loginUser.getUserId());
            }catch (Exception e){

            }
            Date date = new Date();
            this.strictInsertFill(metaObject, "createTime", Date.class, date);
            this.strictUpdateFill(metaObject, "updateTime", Date.class, date);
            this.strictInsertFill(metaObject, "delFlag", String.class, Constants.NO);
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            try{
                this.strictInsertFill(metaObject, "updateBy", String.class, SecurityUtils.getUsername());
            }catch (Exception e){

            }
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        }
    }

}
